import os

from django.core.serializers import serialize
from django.shortcuts import render
from django.views import View
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from shop import settings
from orderapp.models import *
from userapp.models import *
from utils.code import *
from django_redis import get_redis_connection
from userapp import service

# Create your views here.

# 注册界面
class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')


    def post(self, request):
        cname = request.POST.get('cname')
        cpassword = request.POST.get('cpassword')
        email = request.POST.get('email')
        user = User.objects.create(name=cname, password=cpassword, email=email)
        if user:
            request.session['user'] = user
            return HttpResponseRedirect('/')
        return HttpResponseRedirect('/register/')


# 获取邮箱
def email_code(request):
    email = request.GET.get('e')
    print(email)
    # 验证邮件地址格式
    ef = service.verify_email(email)
    if not ef:
        return JsonResponse({'message': '验证失败!'}, status=200)
    # pf:邮件是否发生成功
    pf = service.post_email(email)
    if not pf:
        return JsonResponse({'message': '发送失败!'}, status=200)
    print("发生验证码成功：", email)
    return JsonResponse({'message': 'Reservation deleted successfully!'}, status=200)


#检查邮箱是否已经被绑定
class CheckEmail(View):
    def get(self, request):
        # 获取用户参数
        email = request.GET.get('e')
        print(f'检查邮箱{email}')
        # 根据用户名查找数据库里的用户是否存在
        user_list = User.objects.filter(email=email)  # 如果用get(),没有查找到用户会直接报错，所以用filter()
        flag = False
        if user_list:
            flag = True
        return JsonResponse({'flag': flag})


#检查邮箱验证码是否有误
class CheckEcode(View):
    def get(self, request):
        EMAIL_KEY_TEMPL = 'email:verification:%s'
        vecode = request.GET.get('code','')
        email = request.GET.get('email','')
        print(vecode,email)
        cache = get_redis_connection(alias='verify_codes')
        cache_vecode = cache.get(EMAIL_KEY_TEMPL % email)
        flag = False
        if vecode != cache_vecode:
            flag = True

        return JsonResponse({'flag': flag})








#存入数字验证码
class LoadCodeView(View):
    def get(self,request):
        img, str = gene_code()
        #将验证码存入session
        request.session['session_code'] = str
        return HttpResponse(img, content_type='image/png')


#数字验证码
class CheckCodeView(View):
    def get(self,request):
        #获取GET请求过来的参数
        code = request.GET.get('code')

        #从session中获取存放的验证码
        session_code  = request.session.get('session_code')

        #判断是否相等
        flag = code == session_code
        return JsonResponse({'flag':flag})



# 登录界面
class LoginView(View):
    def get(self, request):
        cname = request.GET.get('cname')
        cpassword = request.GET.get('cpassword')
        user_list = User.objects.filter(name=cname,password=cpassword)
        if user_list:
            request.session['user'] = user_list[0]
            return HttpResponseRedirect('/')

        return render(request,'login.html')

#退出
class LogoutView(View):
    def get(self, request):
        del request.session['user']
        return HttpResponseRedirect('/')

#用户中心
class UsercenterView(View):
    def get(self, request):
        user = request.session.get('user')
        user = User.objects.get(id=user.id)
        order_list = Order.objects.filter(user_id=request.session.get('user').id)
        print(order_list)
        wsum=0
        ysum=0
        for sum in order_list:
            if sum.status == "未支付":
                wsum = wsum +1
            else:
                ysum = ysum +1

        return render(request,'user_center.html',{'wsum':wsum,'ysum':ysum,'user':user})


#地址管理
class AddressView(View):
    def get(self,request):
        user = request.session.get('user')
        user = User.objects.get(id=user.id)
        address_list = user.address_set.all()
        return render(request,'address.html',{'address_list':address_list,'user':user})

    def post(self,request):
        aname = request.POST.get('aname','')
        aphone = request.POST.get('aphone','')
        addr = request.POST.get('addr','')
        user = request.session.get('user')
        Address.objects.create(aname=aname,aphone=aphone,addr=addr,userinfo=user,isdefault=(lambda count:True if count==0 else False)(user.address_set.all().count()))
        address_list = user.address_set.all()
        return render(request,'address.html',{'address_list':address_list})


#读取地址信息表
class LoadAreaView(View):
    def get(self,request):
        # 获取请求参数
        pid = request.GET.get('pid',-1)
        pid = int(pid)

        # 根据父id查询区化信息
        area_list = Area.objects.filter(parentid=pid)

        # 进行序列化
        area_list_json = serialize('json',area_list)

        return JsonResponse({'area_list_json':area_list_json})


#删除地址
class DeladdressView(View):
    def get(self,request,addr_id):
        address = Address.objects.get(id=addr_id)
        address.delete()
        return HttpResponseRedirect('/user/address/')

#我的订单
class MyorderView(View):
    def get(self,request):
        order_list = Order.objects.filter(user_id=request.session.get('user').id)
        print(order_list)
        user = request.session.get('user')
        user = User.objects.get(id = user.id)
        return render(request,'myorder.html',{'order_list':order_list,'user':user})


#删除订单
class DeleteOrderView(View):
    def get(self,request,order_id):
        order = Order.objects.get(id=order_id)
        OrderItem.objects.filter(Order_id=order_id).delete()
        order.delete()
        return HttpResponseRedirect('/user/myorder/')

# 修改个人信息
class SessionView(View):
    def get(self,request):
        user = request.session.get('user')
        user = User.objects.get(id = user.id)
        return render(request, 'usersession.html',{'user':user})

    def post(self, request):
        user = request.session.get('user')
        name = request.POST.get('name','')
        if name == '':
            name = user.name
        sex = request.POST.get('sex','')
        age = request.POST.get('age','')
        phone = request.POST.get('phone','')
        if request.FILES['image']:
            image = request.FILES['image']
            filename = image.name
            print(image,filename)
            # 指定一个目录来保存上传的图片

            upload_dir = settings.STATIC_URL

            # 确保目录存在
            if not os.path.exists(upload_dir):
                os.makedirs(upload_dir)

            full_path = os.path.join(upload_dir, filename)
            print(full_path)
            with open(full_path, 'wb+') as destination:
                for chunk in image.chunks():
                    destination.write(chunk)

            user = User.objects.get(id=user.id)
            user.img = full_path
            user.name = name
            user.sex = sex
            user.ega = age
            user.phone = phone
            user.save()
            return HttpResponseRedirect('/user/usercenter/')
        else:
            print("没有文件")
            # 处理没有文件上传的情况
            return HttpResponseRedirect('/user/usercenter/')

# 修改密码
class MypasswordView(View):
    def get(self, request):
        user = request.session.get('user')
        user = User.objects.get(id = user.id)
        return render(request, 'mypassword.html',{'user':user})

    def post(self, request):
        opassword = request.POST.get('opassword')
        spassword = request.POST.get('spassword')
        user = request.session.get('user')
        print(opassword, spassword)
        if opassword == spassword:
            User.objects.filter(id=user.id).update(password=spassword)
            print("修改成功")
            return HttpResponseRedirect('/user/logout/')
        else:
            return HttpResponseRedirect('/user/mypassword/')


class BjddressView(View):
    def get(self,request,addr_id=1):

        return render(request,'bjaddress.html')
    def post(self,request,addr_id):
        aname = request.POST.get('aname','')
        aphone = request.POST.get('aphone','')
        addr = request.POST.get('addr','')
        Address.objects.filter(id = addr_id).update(aname=aname,aphone=aphone,addr=addr)
        return HttpResponseRedirect('/user/address/')


#默认地址
def ModdressView(request,addr_id):
    address_list = Address.objects.all()
    for address in address_list:
        address.isdefault=0
        address.save()
    Address.objects.filter(id = addr_id).update(isdefault=1)
    return HttpResponseRedirect('/user/address/')
